package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuDao menuDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        // 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 根据条件查询
        Page<Menu> menuPage = menuDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(menuPage.getTotal(), menuPage.getResult());
    }

    @Override
    public void add(Menu menu) {
        // 判断path是否重复
        String path = menu.getPath();
        Integer count = menuDao.findByPath(path);
        if (count > 0) {
            throw new BusinessRuntimeException("路由路径重复");
        }
        // 确认没有重复，执行新增方法
        menuDao.addMenu(menu);
    }

    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    @Override
    public void edit(Menu menu) {
        // 删除原有的菜单
        delMenuById(menu.getId());
        // 添加新的菜单
        add(menu);
    }

    @Override
    public void delMenuById(Integer id) {
        menuDao.delMenuById(id);
    }
}
